from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse,JsonResponse
import json
from ronglian_sms_sdk import SmsSDK

"""图片验证码"""
# 依赖 captcha 扩展包 拷贝到 libs下
class  ImageCodeView(View):
    def get(self,request):
        """
        生成图片验证码
        链接redis 数据库
        入库
        :param request:
        :return:
        """
        data = request.GET
        cur = data.get('cur')
        pre = data.get('pre')
        text,image = captcha.generate_captcha()
        redis_cli = get_redis_connection('code')
        redis_cli.setex(cur,300,text)
        return HttpResponse(image,content_type='image/jpeg')

"""短信验证码"""
# 依赖容联云
class SmsCodeView(View):
    def post(self,request):
        """
        1.接收请求，提取参数，
          验证参数
        2.生成随机验证码
        3.链接数据库
        4.发送短信验证码
        5.返回响应
        :param request:
        :return:
        """
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        id = data.get('id')
        text = data.get('text')
        redis_cli = get_redis_connection('code')
        image_code = redis_cli.get(id)

        if text.lower() != image_code.decode().lower():
            return JsonResponse({'errno':400,'errmsg':'信息错误'})

#         随机验证码
        from random import randint
        sms_code = randint(100000,999999)

        redis_cli.setex(mobile,300,sms_code)
        # 使用容联云发送短信验证码
        # accId = '8aaf0708762cb1cf0176c609243535de'
        # accToken = 'f03d0d5985ee400caf29c2971a75cd9a'
        # appId = '8aaf0708762cb1cf0176c60924fd35e5'
        # sdk = SmsSDK(accId,accToken,appId)
        # """
        # tid:选用模板1
        # mobile：接收短信验证码的手机号
        # datas: 要发送的验证码及有效时间
        # """
        # tid = '1'
        # mobile = '%s'%mobile
        # datas = (sms_code,5)
        # sdk.sendMessage(tid, mobile, datas)

        from celery_tasks.sms.tasks import celery_send_smscode
        celery_send_smscode(mobile,sms_code)
        return JsonResponse({'errno':0,'errmsg':'发送成功'})







